package com.anzuo.app.ui.main

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.LinearLayoutManager
import com.anzuo.app.databinding.FragmentHomeBinding

/**
 * HomeFragment - 首页Fragment
 * 展示如何使用ViewModel和RecyclerView
 * 
 * @author AnZuo
 * @date 2024
 */
class HomeFragment : Fragment() {

    private var _binding: FragmentHomeBinding? = null
    private val binding get() = _binding!!
    
    // 使用viewModels委托来创建ViewModel实例
    private val viewModel: HomeViewModel by viewModels()

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentHomeBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        
        setupRecyclerView()
        observeViewModel()
    }

    /**
     * 设置RecyclerView
     */
    private fun setupRecyclerView() {
        val adapter = HomeAdapter()
        binding.recyclerView.apply {
            layoutManager = LinearLayoutManager(context)
            this.adapter = adapter
        }
    }

    /**
     * 观察ViewModel的数据变化
     */
    private fun observeViewModel() {
        // 观察LiveData数据变化
        viewModel.items.observe(viewLifecycleOwner) { items ->
            // 更新UI
            (binding.recyclerView.adapter as? HomeAdapter)?.submitList(items)
        }
        
        // 观察加载状态
        viewModel.isLoading.observe(viewLifecycleOwner) { isLoading ->
            // 显示/隐藏加载指示器
            binding.progressBar.visibility = if (isLoading) View.VISIBLE else View.GONE
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}

